package com.openx.xoj.controller;

import com.openx.xoj.model.Teacher.ExamQuestion;
import com.openx.xoj.model.entity.Question;
import com.openx.xoj.service.ExaminationQuestionService;
import com.openx.xoj.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/examQuestion")
public class ExaminationQuestionController {

    @Autowired
    private ExaminationQuestionService examinationQuestionService;
    @Autowired
    private QuestionService questionService;

    @PostMapping("/toggle")
    public ResponseEntity<Void> toggleQuestion(@RequestBody Map<String, Object> request) {
        int examId = (Integer) request.get("examId");
        Long questionId = Long.parseLong((String) request.get("questionId"));
        boolean isChecked = (Boolean) request.get("isChecked");

        System.out.println("Received examId: " + examId);
        System.out.println("Received questionId: " + questionId);
        System.out.println("Received isChecked: " + isChecked);

        if (isChecked) {
            // 勾选时插入数据
            examinationQuestionService.addQuestionToExam(examId, questionId);
            System.out.println("Data inserted for examId: " + examId + ", questionId: " + questionId);
        } else {
            // 取消勾选时删除数据
            examinationQuestionService.removeQuestionFromExam(examId, questionId);
            System.out.println("Data deleted for examId: " + examId + ", questionId: " + questionId);
        }
        return ResponseEntity.ok().build(); // 确保请求成功返回
    }

    @GetMapping("/getQuestionsByExamId")
    public ResponseEntity<List<Question>> getQuestionsByExamId(@RequestParam("examId") long examId) {
        System.out.println("id是" + examId);

        // 通过 examId 获取 ExamQuestion 对象列表
        List<ExamQuestion> examQuestions = examinationQuestionService.getQuestionsByExamId(examId);

        // 提取所有的 questionId
        List<Long> questionIds = new ArrayList<>();
        for (ExamQuestion examQuestion : examQuestions) {
            questionIds.add(examQuestion.getQuestionId());
        }

        // 使用 questionIds 从 question 表中查询题目数据
        List<Question> questions = questionService.getQuestionsByIds(questionIds);

        // 返回查询结果
        return ResponseEntity.ok(questions);
    }
}
